<template>
  <div class="content-detail-container">
    <!-- 顶部状态栏 -->
    <div class="status-bar">
      <span class="status-text">{{ getCurrentTime() }}</span>
      <div class="status-icons">
        <span class="icon">📶</span>
        <span class="icon">🔋</span>
      </div>
    </div>

    <!-- 头部导航 -->
    <div class="detail-header">
      <button class="back-btn" @click="$router.back()">←</button>
      <h2 class="header-title">笔记详情</h2>
      <div class="header-right">
        <button class="header-btn">⋯</button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 内容详情 -->
    <div v-else-if="content" class="content-wrapper">
      <!-- 作者信息 -->
      <div class="author-section">
        <div class="author-avatar">
          <img :src="content.author_avatar || 'https://via.placeholder.com/40x40/87CEEB/FFFFFF?text=👤'" :alt="content.author_nickname">
        </div>
        <div class="author-info">
          <div class="author-name">{{ content.author_nickname || '游客' }}</div>
          <div class="publish-time">{{ formatTime(content.created_at) }}</div>
        </div>
      </div>

      <!-- 内容标题 -->
      <h1 class="content-title">{{ content.title || '无标题' }}</h1>

      <!-- 内容正文 -->
      <div class="content-text">{{ content.content }}</div>

      <!-- 媒体内容 -->
      <div v-if="content.media_urls && content.media_urls.length > 0" class="media-section">
        <div 
          v-for="(url, index) in content.media_urls" 
          :key="index"
          class="media-item"
        >
          <img :src="url" :alt="`图片 ${index + 1}`" @error="handleImageError">
        </div>
      </div>

      <!-- 标签 -->
      <div v-if="content.tags && content.tags.length > 0" class="tags-section">
        <span 
          v-for="(tag, index) in content.tags" 
          :key="index"
          class="tag"
        >
          #{{ tag }}
        </span>
      </div>

      <!-- 位置信息 -->
      <div v-if="content.location" class="location-section">
        <span class="location-icon">📍</span>
        <span class="location-text">{{ content.location }}</span>
      </div>

      <!-- 互动统计 -->
      <div class="stats-section">
        <div class="stat-item">
          <span class="stat-icon">👁️</span>
          <span class="stat-value">{{ content.view_count || 0 }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon">❤️</span>
          <span class="stat-value">{{ content.like_count || 0 }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon">⭐</span>
          <span class="stat-value">{{ content.collect_count || 0 }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon">💬</span>
          <span class="stat-value">{{ content.comment_count || 0 }}</span>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button 
          :class="['action-btn', { active: isLiked }]"
          @click="toggleLike"
        >
          <span class="btn-icon">{{ isLiked ? '❤️' : '🤍' }}</span>
          <span class="btn-text">点赞</span>
        </button>
        <button 
          :class="['action-btn', { active: isCollected }]"
          @click="toggleCollect"
        >
          <span class="btn-icon">{{ isCollected ? '⭐' : '☆' }}</span>
          <span class="btn-text">收藏</span>
        </button>
        <button class="action-btn" @click="showCommentInput = !showCommentInput">
          <span class="btn-icon">💬</span>
          <span class="btn-text">评论</span>
        </button>
        <button class="action-btn">
          <span class="btn-icon">📤</span>
          <span class="btn-text">分享</span>
        </button>
      </div>

      <!-- 评论输入框 -->
      <div v-if="showCommentInput" class="comment-input-section">
        <input 
          v-model="commentText"
          type="text"
          placeholder="写下你的评论..."
          class="comment-input"
          @keyup.enter="submitComment"
        />
        <button class="comment-submit-btn" @click="submitComment">发送</button>
      </div>

      <!-- 评论列表 -->
      <div v-if="comments.length > 0" class="comments-section">
        <h3 class="comments-title">评论 ({{ comments.length }})</h3>
        <div 
          v-for="comment in comments" 
          :key="comment.id"
          class="comment-item"
        >
          <div class="comment-avatar">
            <img :src="comment.author_avatar || 'https://via.placeholder.com/30x30/87CEEB/FFFFFF?text=👤'" :alt="comment.author_nickname">
          </div>
          <div class="comment-content">
            <div class="comment-author">{{ comment.author_nickname || '游客' }}</div>
            <div class="comment-text">{{ comment.comment_content }}</div>
            <div class="comment-time">{{ formatTime(comment.created_at) }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-state">
      <div class="error-icon">❌</div>
      <p class="error-message">内容加载失败</p>
      <button class="retry-btn" @click="fetchContent">重试</button>
    </div>

    <!-- 底部导航栏 -->
    <div class="bottom-nav">
      <div class="nav-item" @click="$router.push('/feed')">
        <span class="nav-icon">🏠</span>
        <span class="nav-label">首页</span>
      </div>
      <div class="nav-item">
        <span class="nav-icon">🛒</span>
        <span class="nav-label">购物</span>
      </div>
      <div class="nav-item highlight" @click="$router.push('/publish')">
        <span class="nav-icon-blue">+</span>
        <span class="nav-label">发布</span>
      </div>
      <div class="nav-item">
        <span class="nav-icon">💬</span>
        <span class="nav-label">消息</span>
      </div>
      <div class="nav-item" @click="$router.push('/customer-service')">
        <span class="nav-icon">🛟</span>
        <span class="nav-label">客服</span>
      </div>
      <div class="nav-item" @click="$router.push('/profile')">
        <span class="nav-icon">👤</span>
        <span class="nav-label">我的</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import apiClient from '@/api/axios'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const content = ref(null)
const comments = ref([])
const isLiked = ref(false)
const isCollected = ref(false)
const showCommentInput = ref(false)
const commentText = ref('')

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date()
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now - date
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return date.toLocaleDateString('zh-CN')
}

// 获取内容详情
const fetchContent = async () => {
  const contentId = route.params.id
  if (!contentId) {
    console.error('内容ID不存在')
    return
  }

  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const headers = token ? { 'Authorization': `Bearer ${token}` } : {}
    
    const response = await apiClient.get(`/content/${contentId}`, { headers })
    
    if (response.data.success) {
      content.value = response.data.data
      // 检查是否已点赞/收藏
      if (token && response.data.data.user_interaction) {
        isLiked.value = response.data.data.user_interaction.is_liked || false
        isCollected.value = response.data.data.user_interaction.is_collected || false
      }
    } else {
      console.error('获取内容失败:', response.data.message)
    }
  } catch (error) {
    console.error('获取内容详情失败:', error)
    if (error.response?.status === 404) {
      alert('内容不存在')
      router.back()
    }
  } finally {
    loading.value = false
  }
}

// 获取评论列表
const fetchComments = async () => {
  const contentId = route.params.id
  if (!contentId) return

  try {
    const token = localStorage.getItem('token')
    const headers = token ? { 'Authorization': `Bearer ${token}` } : {}
    
    const response = await apiClient.get(`/content/${contentId}/comments`, { headers })
    
    if (response.data.success) {
      comments.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取评论失败:', error)
  }
}

// 切换点赞
const toggleLike = async () => {
  const token = localStorage.getItem('token')
  if (!token) {
    alert('请先登录')
    router.push('/login')
    return
  }

  try {
    const contentId = route.params.id
    const action = isLiked.value ? 'unlike' : 'like'
    
    await apiClient.post(`/content/${contentId}/${action}`, {}, {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    isLiked.value = !isLiked.value
    if (content.value) {
      content.value.like_count += isLiked.value ? 1 : -1
    }
  } catch (error) {
    console.error('操作失败:', error)
    alert('操作失败，请稍后重试')
  }
}

// 切换收藏
const toggleCollect = async () => {
  const token = localStorage.getItem('token')
  if (!token) {
    alert('请先登录')
    router.push('/login')
    return
  }

  try {
    const contentId = route.params.id
    const action = isCollected.value ? 'uncollect' : 'collect'
    
    await apiClient.post(`/content/${contentId}/${action}`, {}, {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    isCollected.value = !isCollected.value
    if (content.value) {
      content.value.collect_count += isCollected.value ? 1 : -1
    }
  } catch (error) {
    console.error('操作失败:', error)
    alert('操作失败，请稍后重试')
  }
}

// 提交评论
const submitComment = async () => {
  const token = localStorage.getItem('token')
  if (!token) {
    alert('请先登录')
    router.push('/login')
    return
  }

  if (!commentText.value.trim()) {
    return
  }

  try {
    const contentId = route.params.id
    await apiClient.post(`/content/${contentId}/comment`, {
      content: commentText.value.trim()
    }, {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    commentText.value = ''
    showCommentInput.value = false
    await fetchComments()
    if (content.value) {
      content.value.comment_count = (content.value.comment_count || 0) + 1
    }
  } catch (error) {
    console.error('评论失败:', error)
    alert('评论失败，请稍后重试')
  }
}

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.src = 'https://via.placeholder.com/400x400/f0f0f0/999999?text=图片加载失败'
}

// 组件挂载时加载数据
onMounted(() => {
  fetchContent()
  fetchComments()
})
</script>

<style scoped>
.content-detail-container {
  width: 100vw;
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 70px;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 15px;
  background: white;
  font-size: 12px;
}

.status-icons {
  display: flex;
  gap: 5px;
}

/* 头部导航 */
.detail-header {
  background: white;
  padding: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #f0f0f0;
}

.back-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  padding: 5px;
  color: #333;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.header-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  padding: 5px;
  color: #333;
}

/* 加载/错误状态 */
.loading-state, .error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f0f0f0;
  border-top-color: #007AFF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.retry-btn {
  margin-top: 20px;
  padding: 10px 20px;
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}

/* 内容区域 */
.content-wrapper {
  background: white;
  margin-bottom: 10px;
}

.author-section {
  display: flex;
  align-items: center;
  padding: 15px;
  gap: 10px;
}

.author-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.author-name {
  font-weight: bold;
  color: #333;
}

.publish-time {
  font-size: 12px;
  color: #999;
}

.content-title {
  font-size: 20px;
  font-weight: bold;
  padding: 0 15px 15px;
  color: #333;
}

.content-text {
  padding: 0 15px 15px;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
}

.media-section {
  padding: 0 15px 15px;
}

.media-item {
  margin-bottom: 10px;
}

.media-item img {
  width: 100%;
  border-radius: 8px;
}

.tags-section {
  padding: 0 15px 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  color: #007AFF;
  font-size: 14px;
}

.location-section {
  padding: 0 15px 15px;
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
  font-size: 14px;
}

.stats-section {
  padding: 15px;
  display: flex;
  gap: 20px;
  border-top: 1px solid #f0f0f0;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.action-buttons {
  padding: 15px;
  display: flex;
  gap: 15px;
  border-top: 1px solid #f0f0f0;
}

.action-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
  padding: 10px;
  background: none;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn.active {
  background: #f0f8ff;
  border-color: #007AFF;
}

.btn-icon {
  font-size: 20px;
}

.btn-text {
  font-size: 12px;
  color: #666;
}

.comment-input-section {
  padding: 15px;
  display: flex;
  gap: 10px;
  border-top: 1px solid #f0f0f0;
}

.comment-input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  font-size: 14px;
  outline: none;
}

.comment-submit-btn {
  padding: 10px 20px;
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}

.comments-section {
  padding: 15px;
  border-top: 1px solid #f0f0f0;
}

.comments-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.comment-item {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.comment-avatar img {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}

.comment-content {
  flex: 1;
}

.comment-author {
  font-weight: bold;
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
}

.comment-text {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 5px;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

/* 底部导航栏 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 6px 0;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
  font-size: 11px;
  color: #666;
  cursor: pointer;
  flex: 1;
}

.nav-icon {
  font-size: 18px;
}

.nav-icon-blue {
  width: 36px;
  height: 36px;
  background: #007AFF;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: bold;
}

.nav-label {
  font-size: 9px;
}

.highlight .nav-label {
  color: #007AFF;
}
</style>
